//
//  SecurableListDataSource.m
//  Personal Passlock
//
//  Created by 杨岑 on 5/22/15.
//  Copyright (c) 2015 杨岑. All rights reserved.
//

#import "SecurableListDataSource.h"
#import "SecurableCellView.h"
#import "SecurableDataItem.h"
#import "SecurableRowVC.h"


@implementation SecurableListDataSource

+ (instancetype)create
{
    return [[SecurableListDataSource alloc] init];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return self.itemList.count;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    if (row == 0 || row >= self.itemList.count) return nil;
    
    if ([tableColumn.identifier isEqualTo:@"title"])
    {
        SecurableDataItem* dataItem = self.itemList[row];
        SecurableCellView* cellView = [tableView makeViewWithIdentifier:tableColumn.identifier owner:tableColumn];
        cellView.textField.stringValue = dataItem.title;
        cellView.subtitle.stringValue = dataItem.subtitle;
        cellView.imageView.image = dataItem.image;
        return cellView;
    }
    return nil;
}

- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
{
    if (row > 0) return nil;
    
    SecurableRowVC* vc = [[SecurableRowVC alloc] initWithNibName:@"SecurableRowView" bundle:nil];
    [vc loadView];
    
    NSTableRowView* rowView = [[NSTableRowView alloc] init];
    [rowView addSubview:vc.view];
    
    NSDictionary *viewsDictionary = @{@"v": vc.view};
    NSMutableArray* constraints = [NSMutableArray array];
    [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[v]-0-|" options:0 metrics:nil views:viewsDictionary]];
    
    [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[v]-0-|" options:0 metrics:nil views:viewsDictionary]];
    vc.view.translatesAutoresizingMaskIntoConstraints = NO;
    
    [rowView addConstraints:constraints];
    
    return rowView;
}

- (void)tableViewSelectionDidChange:(NSNotification *)notification
{
    if ([self.delegate respondsToSelector:@selector(tableViewSelectionDidChange:)])
    {
        [self.delegate tableViewSelectionDidChange:notification];
    }
}

- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row
{
    return row > 0;
}

@end
